/// Copyright 2007-8 Faraday Media
/// 
/// Licensed under the Apache License, Version 2.0 (the "License"); 
/// you may not use this file except in compliance with the License. 
/// You may obtain a copy of the License at 
/// 
///   http://www.apache.org/licenses/LICENSE-2.0 
/// 
/// Unless required by applicable law or agreed to in writing, software 
/// distributed under the License is distributed on an "AS IS" BASIS, 
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
/// See the License for the specific language governing permissions and 
/// limitations under the License.
using System;
using System.CodeDom;
using System.Reflection;

namespace MetaSharp.XML.Strategies {
  /// <summary>
  /// Strategy for handling a sequence that is visualised as an array.
  /// </summary>
  public class SequenceArrayPropertyStrategy : SequencePropertyStrategy {
    #region IPropertyStrategy Members
    /// <summary>
    /// Checks whether the given strategy applies to a property.
    /// </summary>
    /// <param name="pProp">the property to check</param>
    /// <returns>true - strategies apply</returns>
    public override bool AppliesToProperty(PropertyInfo pProp) {
      return base.AppliesToProperty(pProp) && pProp.PropertyType.IsArray;
    }
    #endregion

    #region SequencePropertyStrategy Members
    /// <summary>
    /// Generates the code to allocate the array.
    /// </summary>
    /// <param name="pContext">the context of the generation</param>
    /// <param name="pProp">the property being generated</param>
    /// <returns>the initialisation expression</returns>
    protected override CodeExpression GetInitResultExpression(GenerationContext pContext, PropertyInfo pProp) {
      return new CodeArrayCreateExpression(
        pProp.PropertyType.GetElementType(),
        new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("elements"), "Length"));
    }

    /// <summary>
    /// Retrieves the type of the elements in the given property.
    /// </summary>
    /// <param name="pProp">the property being generated</param>
    /// <returns>the element type</returns>
    protected override Type GetElementType(PropertyInfo pProp) {
      return pProp.PropertyType.GetElementType();
    }

    /// <summary>
    /// Generates an array index store statement.
    /// </summary>
    /// <param name="pContext">the context of the generation</param>
    /// <param name="pResult">the result object</param>
    /// <param name="pPosition">the expression that retrieves the current position in the element array</param>
    /// <param name="pConverted">the expression that represents the converted value</param>
    /// <returns>the generated statement</returns>
    protected override CodeStatement GetConvertedResultStoreStatement(GenerationContext pContext, CodeExpression pResult, CodeExpression pPosition, CodeExpression pConverted) {
      return new CodeAssignStatement(
        new CodeArrayIndexerExpression(pResult, pPosition), 
        pConverted);
    }

    /// <summary>
    /// The array sequence type does not support an updatable cache - it needs to be invalidated upon updates.
    /// </summary>
    protected override bool HasUpdateableCache {
      get { return false; }
    }


    /// <summary>
    /// Returns the code used to remove an element from the array cache. Since the array cache cannot be updated, returns no code.
    /// </summary>
    /// <param name="pContext">the generation context</param>
    /// <param name="pProp">the property being generated</param>
    /// <param name="pItemExpr">an expression to access the item being removed</param>
    protected override CodeStatement[] GetCacheRemoveStatements(GenerationContext pContext, PropertyInfo pProp,
                                                                CodeExpression pItemExpr) {
      return new CodeStatement[0];
    }

    /// <summary>
    /// Generates code to enumerate through elements in the array.
    /// </summary>
    /// <param name="pContext">the generation context</param>
    /// <param name="pProp">the property being generated</param>
    /// <param name="pHandleItemDelegate">the delegate to be called to check and action the removal</param>
    /// <returns></returns>
    protected override CodeStatement[] GenerateEnumerateForWalk(GenerationContext pContext, PropertyInfo pProp, GenerateHandleItemDelegate pHandleItemDelegate) {
      CodeExpression cacheRef = MethodHelper.GenerateCacheExpression(pProp);

      CodeVariableReferenceExpression indexerExpr = new CodeVariableReferenceExpression("i");
      CodeIterationStatement iterate = new CodeIterationStatement(
        new CodeVariableDeclarationStatement(typeof(int), "i", new CodePrimitiveExpression(0)),
        new CodeBinaryOperatorExpression(indexerExpr, CodeBinaryOperatorType.LessThan, new CodePropertyReferenceExpression(cacheRef, "Length")),
        new CodeAssignStatement(indexerExpr, new CodeBinaryOperatorExpression(indexerExpr, CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1))));

      iterate.Statements.AddRange(pHandleItemDelegate(
        new CodeIndexerExpression(cacheRef, indexerExpr),
        new CodeStatement[] {
          // TODO: Add remove code!
          // No need to backtrack, as we've taken a static snapshot in the array
//          new CodeThrowExceptionStatement(new CodeObjectCreateExpression(typeof(NotImplementedException)))
        }));

      return new CodeStatement[] { iterate };
    }
    #endregion
  }
}
